package com.example.clock;
import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;
import static android.app.ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE;
import static com.example.clock.R.id.imageButton;
import static com.example.clock.R.id.imageButton10;
import static com.example.clock.R.id.imageButton3;
import static com.example.clock.R.id.imageButton4;
import static com.example.clock.R.id.textView6;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;


import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.media.Image;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.clock.basicClass.Task;

import java.util.List;

public class LockActivity extends AppCompatActivity {

    private Task task;

    private ImageButton btnSubmit1,btnSubmit2,btnSubmit3,btnSubmit4;

    private int timeleft;


    private TextView tvCountdown;
    private CountDownTimer countDownTimer;
    private long timeLeftInMillis;

    private PopupWindow mPopWindow;

    private boolean lockFinished = false;
    private boolean timeDisplayStyle = false;

    private boolean lockClass;

    private int lockRemaining=2;  //for test




    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lock);

        //Note:由于新版android操作系统不会将点击Home键事件传递给应用APP，因此无法直接屏蔽Home键
        //解决方案：提示用户Home键可在紧急情况下使用，但是已锁屏时间将被清零，请慎用
        //用户在点击Home键后，应用程序将进入后台，通过检测应用程序是否在前后台运行，详见isAppInForeground()
        //如果是在后台运行，则不会保留已锁屏时间
        Toast.makeText(getApplicationContext(), "温馨提示：锁屏期间手机导航键区域的返回键和任务键暂时不能使用；" +
                "主页键可在紧急情况下使用，但是已锁屏时间将被清零，请慎用。", Toast.LENGTH_LONG).show();


        tvCountdown = findViewById(R.id.textView9);

        //通过Serializable方法获取设置界面传送来的锁屏配置数据
        Transport transport1=(Transport) getIntent().getSerializableExtra("Serializable");
        timeleft = Integer.parseInt(transport1.getDuration());//锁屏时长
        lockClass = transport1.getType();
        TextView primaryclass=(TextView)findViewById(R.id.textView13);
        primaryclass.setText(transport1.getPc());//一级事件
        TextView secondaryclass=(TextView)findViewById(R.id.textView14);
        secondaryclass.setText(transport1.getSc());//二级事件
        TextView locknote=(TextView)findViewById(R.id.textView15);
        locknote.setText("备注:  "+transport1.getEventnote());//备注
        locknote.setTextColor(Color.GRAY);
        TextView taskName=(TextView)findViewById(R.id.textView16);
        taskName.setText("事件名："+transport1.getTaskName());//任务名

        //倒计时
        int hour = timeleft/60;
        int minute = timeleft - hour*60;
        startCountdown(hour,minute);

        }

        //判断app是否在前台运行
        private boolean isAppInForeground() {
            boolean isInForeground=false;
            ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
            List<ActivityManager.RunningAppProcessInfo> processInfoList = manager.getRunningAppProcesses();
            for (ActivityManager.RunningAppProcessInfo processInfo : processInfoList) {
                if (processInfo.processName.startsWith("com.example.clock")) {
                    isInForeground =  processInfo.importance == IMPORTANCE_FOREGROUND;
                    break;
                }
            }
            return isInForeground;
        }


    //屏蔽导航键区域的任务键
    @Override
    protected void onPause() {
        super.onPause();
        ActivityManager activityManager = (ActivityManager) getApplicationContext()
                .getSystemService(Context.ACTIVITY_SERVICE);
        activityManager.moveTaskToFront(getTaskId(), 0);

    }



    //屏蔽导航键区域的返回键
    @Override
    public void onBackPressed() {
        Toast.makeText(getApplicationContext(), "温馨提示：锁屏期间手机导航键区域的返回键和任务键暂时不能使用；" +
                "主页键可在紧急情况下使用，但是已锁屏时间将被清零，请慎用。", Toast.LENGTH_LONG).show();
    }

    //屏幕顶部箭头键处理
    public void onClickArrow(View view){

        if (lockClass == true) { //读取并判断锁屏类型
            Toast.makeText(LockActivity.this, "已经是严格模式，不能升级", Toast.LENGTH_SHORT).show();
        }
        else{
            upgradeConfirm();  //锁屏类型升级处理
        }

    }


    //屏幕顶部解锁键处理
    public void onClickLock(View view){

        ////从数据库获取强制解锁剩余次数 lockRemaining

        if (!lockFinished ){

            if (lockClass == false)  //读取并判断锁屏类型
            {
                ////组装task数据，并保存到数据库
                finish();
            }

            else {
                if (lockRemaining>0) {
                    unlockConfirm();  //强制解锁确认或取消处理
                }
                else{
                    Toast.makeText(LockActivity.this, "本月强制解锁额度已用完，不能强制解锁", Toast.LENGTH_SHORT).show();}
            }

        }
        else{
            ////组装task数据，并保存到数据库
            finish();
        }


    }

    //屏幕顶部三点键处理
    public void onClickThreePoint(View view){

        //显示事件信息
        View layout = findViewById(R.id.constraintLayout);
        layout.setVisibility(View.VISIBLE);

    }

    //task框内右上部X键处理
    public void onClickCross(View view) {

        //隐藏事件信息
        View layout = findViewById(R.id.constraintLayout);
        layout.setVisibility(View.INVISIBLE);

    }

    //锁屏时间显示切换按钮处理
    public void onClickChangeStyle(View view){
        timeDisplayStyle = !timeDisplayStyle;
    }

    private void startCountdown(int hour, int minute) {
        // 计算剩余时间的毫秒数
        timeLeftInMillis = (hour * 60 + minute) * 60 * 1000;

        
        // 开始倒计时
       countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
            @Override
            //每个一秒执行锁屏时间更新
            public void onTick(long millisUntilFinished) {
                if (isAppInForeground()) {   //判断是否在前台运行
                    timeLeftInMillis = millisUntilFinished;
                    updateCountdownText();
                }
                else {
                   finish();//用户点击Home键，直接退出锁屏界面，已锁屏时间不予保留
                }
            }

            @Override
            public void onFinish() {  //倒计时结束时的处理
                TextView lockend;
                lockend = findViewById(R.id.textView6);
                lockend.setText(String.format("锁屏结束,请按解锁键返回"));
                tvCountdown.setText(String.format("剩余时间: %02d:%02d:%02d ", 0, 0, 0));
                lockFinished = true;   //设置锁屏已结束标志
            }

        }.start();
    }

    //显示倒计时
    private void updateCountdownText() {
        int hours = (int) (timeLeftInMillis / 1000 / 3600);
        int minutes = (int) ((timeLeftInMillis / 1000) % 3600 / 60);
        int seconds = (int) (timeLeftInMillis / 1000 % 60);

        int pastHours = (int) ((timeleft*60*1000 -timeLeftInMillis )/1000/3600);
        int pastMinutes = (int) ((((timeleft * 60 * 1000 - timeLeftInMillis) / 1000) % 3600) / 60);
        int pastSeconds = (int) (60 - seconds);
        if (pastSeconds == 60) {
            pastSeconds = 0;
            pastMinutes = pastMinutes + 1;
        }

        //根据用户选择显示锁屏时间或锁屏倒计时
        if (timeDisplayStyle) {
            tvCountdown.setText(String.format("锁屏倒计时: %02d:%02d:%02d ", hours, minutes, seconds));
        } else {
            tvCountdown.setText(String.format("锁屏时间: %02d:%02d:%02d ", pastHours, pastMinutes, pastSeconds));
        }
    }


    //锁屏类型升级处理
    private void upgradeConfirm(){
        //获取自定义view
        View mDialogView = LayoutInflater.from(this).inflate(R.layout.upgrade_confirm, null);
        mPopWindow = new PopupWindow(mDialogView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, false);
        mPopWindow.setOutsideTouchable(false);
        //显示弹窗
        View rootview = LayoutInflater.from(this).inflate(R.layout.activity_lock, null);
        mPopWindow.showAtLocation(rootview, Gravity.CENTER,0, 0);

        //弹窗以外界面变灰
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.3f;
        getWindow().setAttributes(lp);

        //设置弹窗提示
        int timeLeftHours = (int) (timeLeftInMillis / 1000 / 3600);
        int timeLeftMinutes = (int) ((timeLeftInMillis / 1000) % 3600 / 60);
        //TextView tv=(TextView)mPopWindow.getContentView().findViewById(R.id.textView23);
        TextView tv=(TextView)mDialogView.findViewById(R.id.textView23);
        if(timeLeftHours>0) {
            tv.setText("     接下来将升级到需要等待" + timeLeftHours + "小时" + timeLeftMinutes + "分钟后解锁，请确认没有紧急事件后再升级");
        }
        else{
            tv.setText("     接下来将升级到需要等待"+ timeLeftMinutes + "分钟后解锁，请确认没有紧急事件后再升级");
        }
        tv.setTextColor(Color.BLACK);

        //取消升级按钮处理
        Button bt_cancel=(Button)mDialogView.findViewById(R.id.button3);
        bt_cancel.setBackgroundColor(Color.YELLOW);
        bt_cancel.setTextColor(Color.BLACK);
        bt_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopWindow.dismiss();//关闭弹窗

                //恢复界面正常
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });

        //确定升级按钮处理
        Button bt_ok=(Button)mDialogView.findViewById(R.id.button2);
        bt_ok.setBackgroundColor(Color.CYAN);
        bt_ok.setTextColor(Color.BLACK);
        bt_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                lockClass = true;  //锁屏升级
                mPopWindow.dismiss();  //关闭弹窗

                //恢复界面正常
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
    }


    private void unlockConfirm(){
        //获取自定义view
        View mDialogView = LayoutInflater.from(this).inflate(R.layout.unlock_confirm, null);
        mPopWindow = new PopupWindow(mDialogView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, false);
        mPopWindow.setOutsideTouchable(false);
        //显示PopupWindow
        View rootview = LayoutInflater.from(this).inflate(R.layout.activity_lock, null);
        mPopWindow.showAtLocation(rootview, Gravity.CENTER,0, 0);

        //弹窗以外界面变灰
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.3f;
        getWindow().setAttributes(lp);

        //设置弹窗提示
        TextView tv=(TextView)mPopWindow.getContentView().findViewById(R.id.textView20);
        ////从数据库获取强制解锁剩余次数 lockRemaining
        tv.setText("      强制解锁本月还剩余" + lockRemaining + "次机会，您确定要强制结束?");
        tv.setTextColor(Color.BLACK);
        tv.setTextSize(18);


        //取消解锁按钮处理
        Button bt_cancel=(Button)mDialogView.findViewById(R.id.button5);
        bt_cancel.setBackgroundColor(Color.YELLOW);
        bt_cancel.setTextColor(Color.BLACK);
        bt_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopWindow.dismiss();  //关闭弹窗

                //恢复界面正常
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });

        //确定升级按钮处理
        Button bt_ok=(Button)mDialogView.findViewById(R.id.button4);
        bt_ok.setBackgroundColor(Color.CYAN);
        bt_ok.setTextColor(Color.BLACK);
        bt_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ////lockRemaining 次数减 1，并保存到数据库
                ////组装task数据，并保存到数据库

                mPopWindow.dismiss();  //关闭弹窗

                //恢复界面正常
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);

                finish();//退出锁屏界面
            }
        });
    }

}
